<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col :span="4">
          <el-button type="primary" @click="addCategoriesShow">添加分类</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="shopData"
        style="width: 100%;margin-bottom: 20px;"
        row-key="cat_id"
        border
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="cat_name" label="分类名称"></el-table-column>
        <el-table-column prop="cat_deleted" label="是否有效" align="center">
          <template slot-scope="scope">
            <i v-if="!scope.row.cat_deleted" class="el-icon-success" style="color:green"></i>
            <i v-else class="el-icon-error" style="color:red"></i>
          </template>
        </el-table-column>
        <el-table-column prop="cat_level" label="排序" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.cat_level===0">一级</el-tag>
            <el-tag v-else-if="scope.row.cat_level===1" type="success">二级</el-tag>
            <el-tag v-else type="info">三级</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editShop(scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeCate(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="total,prev, pager, next,jumper"
        :total="total"
        :page-size="queryInfo.pagesize"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog title="提示" :visible.sync="addCategoriesDialogVisible" width="50%" @close="resetForm">
      <el-form
        :model="addCategoriesForm"
        :rules="addCategoriesRules"
        ref="addCategoriesRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCategoriesForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectedCateList"
            :options="parentCateList"
            :props="{ expandTrigger: 'hover',value: 'cat_id',label: 'cat_name',children: 'children' }"
            @change="handleChange"
            change-on-select
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCategoriesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改分类对话框 -->
    <el-dialog title="提示" :visible.sync="editDialogVisible" width="50%">
      <el-form ref="editFormRef" :model="editForm" label-width="100px" :rules="addCategoriesRules">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="editForm.cat_name" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "categories",
  data() {
    return {
      queryInfo: {
        type: "", //获取所有级别的分类
        pagenum: 1, //当前页码值
        pagesize: 5 //每页显示多少条数据
      },
      shopData: [], //商品分类表格数据
      total: 0, //商品分类总条数
      addCategoriesDialogVisible: false, //添加分类对话框
      addCategoriesForm: {
        cat_pid: "", //分类父 ID
        cat_name: "", //分类名称
        cat_level: "" //分类层级
      },
      addCategoriesRules: {
        //添加分类校验规则
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      parentCateList: [], //添加分类数据列表
      selectedCateList: [], //添加分类当前选中数据
      editDialogVisible: false, //修改对话框
      editForm: {
        cat_name: ""
      }
    };
  },
  methods: {
    async getCategories() {
      //获取商品分类列表数据
      const { data: res } = await this.$axios.get("categories", {
        params: this.queryInfo
      });
      if (res.meta.status === 200) {
        this.shopData = res.data.result;
        this.total = res.data.total;
      }
    },
    handleCurrentChange(newPage) {
      //改变页码请求数据
      this.queryInfo.pagenum = newPage;
      this.getCategories();
    },
    addCategoriesShow() {
      //添加分类对话框
      this.addCategoriesDialogVisible = true;
      this.getgetCategoriesList();
    },
    async getgetCategoriesList() {
      //获取对话框商品分类列表数据
      const { data: res } = await this.$axios.get("categories", {
        params: { type: 2 }
      });
      if (res.meta.status === 200) {
        this.parentCateList = res.data;
      }
    },
    handleChange() {
      //添加分类选择器改变触发
      if (this.selectedCateList.length === 0) {
        // 证明没有选中任何父级分类
        this.addCategoriesForm.cat_pid = 0;
        this.addCategoriesForm.cat_level = 0;
      } else {
        // 选中父级分类
        this.addCategoriesForm.cat_pid = this.selectedCateList[
          this.selectedCateList.length - 1
        ];
        // 设置分类等级
        this.addCategoriesForm.cat_level = this.selectedCateList.length;
      }
    },
    addCate() {
      //添加分类按钮
      this.$refs.addCategoriesRuleForm.validate(async vaild => {
        if (!vaild) return;
        const { data: res } = await this.$axios.post(
          "categories",
          this.addCategoriesForm
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加分类失败！");
        }
        this.$message.success("添加分类成功！");
        this.addCategoriesDialogVisible = false;
        this.getCategories();
      });
    },
    resetForm() {
      //关闭对话框后，重置表单
      this.$refs.addCategoriesRuleForm.resetFields();
      this.selectedCateList = [];
      this.addCategoriesForm.cat_level = 0;
      this.addCategoriesForm.cat_pid = 0;
    },
    editShop(row) {
      //修改对话框
      this.editDialogVisible = true;
      this.editForm.cat_name = row.cat_name;
      this.editId = row.cat_id;
    },
    editCate() {
      this.$refs.editFormRef.validate(async vaild => {
        if (!vaild) return;
        const { data: res } = await this.$axios.put(
          `categories/${this.editId}`,
          { cat_name: this.editForm.cat_name }
        );
        // if (res.meta.status !== 201) {
        //   return this.$message.error("修改分类失败！");
        // }
        // this.$message.success("修改分类成功！");
        if (res.meta.status === 200) {
          this.$message.success("修改分类成功！");
          this.getCategories();
        } else {
          return this.$message.error("修改分类失败！");
        }
        this.editDialogVisible = false;
      });
    },
    async removeCate(row) {
      //删除用户
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => error);
      if (res === "confirm") {
        const { data: res } = await this.$axios.delete(
          `categories/${row.cat_id}`
        );
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg);
           this.getCategories();
        } else {
          this.$message.error(res.meta.msg);
        }
      } else {
        this.$message.error("取消删除");
      }
    }
  },
  created() {
    this.getCategories();
  }
};
</script>

<style scoped>
.el-card {
  margin-top: 30px;
}
.el-table {
  margin-top: 30px;
}
</style>